<template>
   <div class="user-form">
    <cell-group :border="false" >
  <cell title=""  size="large" :to="'/'">
     <!-- 使用 right-icon 插槽来自定义右侧图标 -->
  <template #right-icon >
    <icon name="cross" class="cross" />
  </template>
  </cell>
</cell-group>
<div>
      <h1>宝甄</h1>
      <h2>欢迎来到宝甄</h2>
     </div>
 <Form @submit="onSubmit">
  <cell-group inset>
    <field
      v-model="phone"
      name="mobile"
      placeholder="请输入手机号"
      :error-message="error" 
      @blur="confirm"
    />
    <field
    v-model="sms"
    center
    name="code"
    clearable
    placeholder="请输入短信验证码"
  >
    <template #button>
      <Button size="small" type="primary" @click="codeHandle">发送验证码</Button>
    </template>
  </field>
  </cell-group>
  <checkbox v-model="checked" checked-color="#FFC731" style="padding: 20px 20px;">
    未注册的手机号登录后将自动生成账号，且代表您已阅读并同意《用户协议》和《隐私政策》
  </checkbox>
  <div style="margin: 16px;">
    <Button round block type="primary" color="#FFC731" style="color:#272727; font-size:20px;font-weight: bold;" native-type="submit">
      登录
    </Button>
  </div>
  <!-- <div style="margin: 16px;">
    <Button round block type="default" :to="{ name: 'Reg' }">
      注册
    </Button>
  </div> -->
</Form>
  <router-link :to="{ name: 'AccountLogin' }" >
    密码登录
  </router-link>
</div>
</template>
<style>
.user-form {
  padding: 8px;
}
a{
    display: block;
    text-align: center;
    color: #6D6D6D;
  }
  .van-checkbox__label{
  font-size:.4rem;
  color: #575757 
}
</style>
<script setup>
import { ref } from "vue";
import { useRouter } from "vue-router";
import { setToken } from "../utils/tools";
import {stringify} from "qs";
import { codeAPI,loginAPI } from "../services/auth";
import { Form, Field, CellGroup,Button,Toast,Cell,Icon ,Checkbox} from 'vant';
const phone = ref("");
const error = ref("");
const sms = ref("");
const checked=ref(true);
const router = useRouter();
const { replace } = useRouter();
var flag=0;
var code='';
// 验证手机号格式
const confirm=()=>{
  var reg=/^1(3|4|5|6|7|8|9)\d{9}$/;
  if (reg.test(phone.value)){
     error.value="";
     flag=1;
  }else{
     error.value="手机号格式错误";
  }
}
// 接收验证码
const codeHandle=async()=>{
   if(flag==1){
     const res=await codeAPI({mobile:phone.value});
     if(res.code){
      Toast.success("您的验证码是"+res.data);
      code=res.data;
     }
   }else{
    alert("请先输入手机号");
   }
}

//登录验证
const onSubmit = (values) => {
  if(checked.value){
  loginAPI(stringify(values)).then((res) => {
    if (res.code == 200) {
      Toast.success("登录成功");
      setToken(res.data);
       // 跳转
       replace({
        name: "User",
      });
    } else {
      Toast.fail(res.msg);
    }
  });
}else{
  Toast.fail('请先勾选用户协议');
}
};

</script>
